package com.b2c.ftysys.sevice.impl;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.directwebremoting.annotations.RemoteProxy;
import org.directwebremoting.create.NewCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.b2c.ftysys.dao.B2cFsyRouteDAO;
import com.b2c.ftysys.dao.B2cFsyWdDAO;
import com.b2c.ftysys.dao.DatabaseException;
import com.b2c.ftysys.domain.B2cFsyRoute;
import com.b2c.ftysys.domain.B2cFsyRouteExample;
import com.b2c.ftysys.domain.B2cFsyWd;
import com.b2c.ftysys.domain.B2cFsyWdExample;
import com.b2c.ftysys.domain.ExampleFactory;
import com.b2c.ftysys.domain.PageResult;
import com.b2c.ftysys.domain.Product;
import com.b2c.ftysys.helper.ObjectUtils;
import com.b2c.ftysys.helper.ProductUtils;
import com.b2c.ftysys.sevice.ProductService;
import com.b2c.ftysys.sevice.RouteService;
import com.b2c.ftysys.sevice.ServicesException;
import com.b2c.ftysys.view.application.AppErrorException;
import com.b2c.ftysys.view.application.fileImport.FileImport;

@Service
@RemoteProxy(creator = NewCreator.class, name = "routeService")
public class RouteServiceImpl implements RouteService {
	@Autowired
	private B2cFsyRouteDAO dao = null;

	@Autowired
	private B2cFsyWdDAO wdDao = null;;

	@Autowired
	private ProductService productService = null;

	@Resource(name = "routeSettingImportor")
	private FileImport routeSettingImportor = null;

	public B2cFsyRouteDAO getDao() {
		return dao;
	}

	public void setDao(B2cFsyRouteDAO dao) {
		this.dao = dao;
	}

	public int delRoute(String routeType) {
		B2cFsyRouteExample example = new B2cFsyRouteExample();
		example.createCriteria().andRouteTypeEqualTo(routeType);
		return dao.deleteByExample(example);
	}

	@SuppressWarnings("unchecked")
	public List<String> getAllRouteType() {
		try {
			return dao.getSqlClient().queryForList("getAllRouteType");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public List<Map<String, Object>> getRouteByRouteType(String routeType) {
		if (StringUtils.isEmpty(routeType))
			return null;
		try {
			return dao.getSqlClient().queryForList("getRoute", routeType);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public boolean isLastWsId(String ftySku, Integer wsId) {
		Product product = productService.getProductByFtySku(ftySku);

		if (StringUtils.isEmpty(product.getRouteId())) {
			return false;
		}

		if (null == wsId)
			return false;

		List<Map<String, Object>> routes = this.getRouteByRouteType(ftySku,
				product.getRouteId());

		if (null == routes || routes.size() <= 0)
			return false;
		int laseWsId = (Integer) routes.get(routes.size() - 1).get("wsId");

		return laseWsId == wsId;
	}

	/**
	 * 获取最后一个在制编号
	 * 
	 * @param ftySku
	 * @return
	 */
	public int getLastWipId(String ftySku) {
		if (null == ftySku)
			return 0;
		Product product = productService.getProductByFtySku(ftySku);
		if (StringUtils.isEmpty(product.getRouteId())) {
			return 0;
		}
		List<Map<String, Object>> routes = this.getRouteByRouteType(ftySku,
				product.getRouteId());
		if (null == routes || routes.size() <= 0)
			return 0;
		Object obj = routes.get(routes.size() - 1).get("wipId");
		if (obj == null || !(obj instanceof Integer))
			return 0;
		return (Integer) obj;
	}

	public int getFtySkuNowWsId(String ftySku) {
		Product product = productService.getProductByFtySku(ftySku);

		if (StringUtils.isEmpty(product.getRouteId())) {
			return 0;
		}

		List<Map<String, Object>> routes = this.getRouteByRouteType(ftySku,
				product.getRouteId());

		for (Map<String, Object> route : routes) {
			if (route.get("staffId") instanceof Integer) {
				continue;
			} else if (route.get("staffId") instanceof String) {
				if (StringUtils.isEmpty((String) (route.get("staffId"))))
					return (Integer) route.get("wsId");
			}
			if (null == route.get("staffId"))
				return (Integer) route.get("wsId");
		}
		return -1;
	}

	/**
	 * 获取在制产品的上一个在制编号
	 * 
	 * @param ftySku
	 * @return
	 */
	public int getFtySkuPrevWipId(String ftySku) {
		Product product = productService.getProductByFtySku(ftySku);

		if (StringUtils.isEmpty(product.getRouteId())) {
			return 0;
		}

		List<Map<String, Object>> routes = this.getRouteByRouteType(ftySku,
				product.getRouteId());

		int lastRouteId = 0;

		for (Map<String, Object> route : routes) {
			if (route.get("staffId") instanceof Integer) {
				lastRouteId = (Integer) route.get("wipId");
				continue;
			} else if (route.get("staffId") instanceof String) {
				if (StringUtils.isEmpty((String) (route.get("staffId"))))
					return lastRouteId;
			}
			if (null == route.get("staffId"))
				return lastRouteId;
		}
		return 0;
	}

	@SuppressWarnings("unchecked")
	public List<Map<String, Object>> getRouteByRouteType(String ftySku,
			String routeType) {
		if (StringUtils.isEmpty(routeType))
			return null;

		if (StringUtils.isEmpty(ftySku))
			return getRouteByRouteType(routeType);

		try {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put("proSku", ftySku);
			dataMap.put("routeType", routeType);

			List<Map<String, Object>> skuRoutes = dao.getSqlClient()
					.queryForList("getRouteBySku", dataMap);
			// List<Map<String, Object>> temps = new ArrayList<Map<String,
			// Object>>();
			if (null != skuRoutes && skuRoutes.size() > 0) {
				// temps.addAll(skuRoutes);
				// List<Map<String, Object>> routes =
				// getRouteByRouteType(routeType);
				// for (Map<String, Object> route : routes) {
				// boolean flag = true;
				// for (Map<String, Object> skuRoute : skuRoutes) {
				// if (route.containsValue(skuRoute.get("wsId")))
				// flag = false;
				// }
				// if (flag)
				// temps.add(route);
				// }
				return skuRoutes;
			} else
				return getRouteByRouteType(routeType);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public int regRoute(String routeType, String[] route) {
		if (route == null || route.length <= 0)
			return 0;
		else if (routeType == null || routeType.trim().length() <= 0) {
			return 0;
		}

		B2cFsyRouteExample example = new B2cFsyRouteExample();
		example.createCriteria().andRouteTypeEqualTo(routeType);
		if (dao.countByExample(example) > 0)
			return -1;
		int num = 0;
		B2cFsyRoute routeObj = null;
		for (int i = 0; i < route.length; i++) {
			if (route[i] == null)
				continue;// Ϊ�ռ���ѭ��
			int ws = 0;
			try {
				ws = Integer.parseInt(route[i]);
			} catch (Exception e) {
				// ��������,�����ѭ��
				continue;
			}

			routeObj = new B2cFsyRoute();
			routeObj.setWsId(ws);
			routeObj.setRouteType(routeType);
			try {
				if (i != 0)
					routeObj.setPrevWsId(Integer.parseInt(route[i - 1]));

				if (i < route.length - 1)
					routeObj.setNextWsId(Integer.parseInt(route[i + 1]));
			} catch (Exception e) {
			}

			dao.save(routeObj);
			num++;
		}

		return num;
	}

	public PageResult getRouteSettingByPage(PageResult page)
			throws ServicesException {
		page.setCountMappedId("b2c_fsy_wd.abatorgenerated_countByExample");
		page
				.setSelectDataMappedId("b2c_fsy_wd.abatorgenerated_selectByExample");
		try {
			return this.wdDao.getListByPage(page);
		} catch (DatabaseException e) {
			throw new ServicesException(e);
		}
	}

	/**
	 * 根据款号获取预先设置好的路由设置
	 * 
	 * @param styleNo
	 * @return
	 */
	public B2cFsyWd getRouteSettingByStyleNo(String styleNo) {
		B2cFsyWdExample example = ExampleFactory.createWdExample();
		example.createCriteria().andProStyleNoEqualTo(styleNo);

		List<B2cFsyWd> wds = wdDao.selectByExample(example);
		if (null == wds || wds.size() <= 0)
			return null;

		return wds.get(0);
	}

	/**
	 * 根据工厂Sku号获取预先设置好的路由设置
	 * 
	 * @param ftySku
	 * @return
	 */
	public B2cFsyWd getRouteSettingByFtySku(String ftySku) {
		return getRouteSettingByStyleNo(ProductUtils.getStyleNoByFtySku(ftySku));
	}

	/**
	 * 根据客户Sku获取预先设置好的路由设置
	 * 
	 * @param sku
	 * @return
	 */
	public B2cFsyWd getRouteSettingBySku(String sku) {
		return getRouteSettingByStyleNo(ProductUtils.getStyleNoByCmtSku(sku));
	}

	/**
	 * 新增预设路由
	 * 
	 * @param wd
	 */
	public void regRouteSetting(B2cFsyWd wd) {
		if (null == wd || StringUtils.isEmpty(wd.getRouteType())
				|| StringUtils.isEmpty(wd.getProStyleNo()))
			return;

		B2cFsyWdExample example = ExampleFactory.createWdExample();

		example.createCriteria().andRouteTypeEqualTo(wd.getRouteType())
				.andProStyleNoEqualTo(wd.getProStyleNo());
		if (this.wdDao.countByExample(example) <= 0)
			this.wdDao.save(wd);
		else
			return;
	}

	/**
	 * 更新预设路由
	 * 
	 * @param wd
	 */
	public void updateWdByExample(B2cFsyWd wd) {
		if (null == wd || null == wd.getWdId())
			return;
		this.wdDao.updateByPrimaryKeySelective(wd);
	}

	/**
	 * 删除预设路由
	 * 
	 * @param wdId
	 */
	public void delRouteSetting(Integer wdId) {
		this.wdDao.deleteByPrimaryKey(wdId);
	}

	public int importRouteSetting(String fileAddr) throws ServicesException {
		int iNum = 0;
		try {
			List<Map<String, Object>> dataList = routeSettingImportor
					.importData(fileAddr);
			for (Map<String, Object> dataMap : dataList) {
				try {
					B2cFsyWd wd = (B2cFsyWd) ObjectUtils.mapToObj(dataMap,
							B2cFsyWd.class);
					regRouteSetting(wd);
					iNum++;
				} catch (Exception e) {
					e.printStackTrace();
					continue;
				}
			}
			return iNum;
		} catch (AppErrorException e) {
			e.printStackTrace();
			throw new ServicesException(e);
		}
	}
}
